#include <iostream>
#include <stdlib.h>
#include <cstring>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

void Usage(const std::string &proc)
{
    std::cout << "#Usage: " << proc << "socketip socketport" << std::endl;
}

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    std::string socketip;
};

void *Recv_message(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    // 2.接收数据
    char buffer[1024];
    while (true)
    {
        memset(buffer, 0, sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        int s = recvfrom(td->sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&temp, &len);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << buffer << std::endl;
        }
    }
}
void *Send_message(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    // 绑定--client也要绑定，只不过不要用户显示绑定而已，一般由os自由随机选择
    // 一个端口只能被一个进程bind,server是，client也是
    //  对于client的端口号是什么不重要，我只要保证主机上唯一即可
    // 系统中什么时候给我bind呢？首次发生数据的时候
    std::string message;
    char buffer[1024];
    socklen_t len = sizeof(td->server);
    std::string welcome = td->socketip;
    welcome += " comming...";
    int sendresult = sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&(td->server), len);
    if (sendresult < 0)
    {
        perror("sendto");
    }
    while (true)
    {
        std::cout << "Please Enter@ ";
        getline(std::cin, message);
        // 1.数据 2.给谁发

        sendresult = sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&(td->server), len);
        if (sendresult < 0)
        {
            perror("sendto");
        }
    }
}

// 实现UDP客户端，用于向UDP服务器发生数据并相应
// 可执行程序+IP+端口
int main(int argc, char *argv[])
{
    std::cout << "hello client" << std::endl;
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string socketip = argv[1];
    uint16_t socketport = std::stoi(argv[2]);

    // 初始化服务器地址
    struct ThreadData td;

    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(socketport);
    // 易错，这里不能td.socketip.c_str(),不然传不过去！
    td.server.sin_addr.s_addr = inet_addr(socketip.c_str());
    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        std::cout << "socket err" << std::endl;
        return 1;
    }

    pthread_t recvid, sendid;
    pthread_create(&sendid, nullptr, Send_message, &td);

    pthread_create(&recvid, nullptr, Recv_message, &td);

    pthread_join(recvid, nullptr);
    pthread_join(sendid, nullptr);

    close(td.sockfd);
    return 0;
}